using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 混乱Buff - 使目标随机移动和攻击
/// </summary>
public class ConfuseBuff : BuffBase
{
    private Vector3 m_RandomDirection;
    private float m_ConfuseSpeed;
    private float m_LastDirectionChangeTime;
    private float m_DirectionChangeInterval = 1.0f; // 每秒改变一次方���

    public ConfuseBuff(BuffData buffData, Entity caster, Entity target) : base(buffData, caster, target)
    {
        if (buffData is ConfuseData confuseData)
        {
            m_ConfuseSpeed = confuseData.ConfuseSpeed;
            m_DirectionChangeInterval = confuseData.DirectionChangeInterval;
        }
        else
        {
            m_ConfuseSpeed = 3.0f; // 默认混乱速度
        }
        
        // 设置初始随机方向
        m_RandomDirection = Random.insideUnitCircle.normalized;
    }

    protected override void OnStart()
    {
        base.OnStart();
        
        m_LastDirectionChangeTime = Time.time;
        
        // 播放混乱特效
        if (BuffData.Effect != null)
        {
            var effect = GameObject.Instantiate(BuffData.Effect, Target.transform);
            effect.transform.localPosition = Vector3.zero;
        }
        
        // 设置动画状���
        if (Target.Animator != null)
        {
            Target.Animator.SetBool("confused", true);
        }
        
        Logger.Log($"{Target.name} 陷入混乱，行为变得不可预���");
    }

    protected override void OnTick(float dt)
    {
        base.OnTick(dt);
        
        // 定期改变移动方向
        if (Time.time - m_LastDirectionChangeTime >= m_DirectionChangeInterval)
        {
            m_RandomDirection = Random.insideUnitCircle.normalized;
            m_LastDirectionChangeTime = Time.time;
        }
        
        // 执行混乱移动
        if (Target.MoveComponent != null)
        {
            Vector3 currentPos = Target.transform.position;
            Vector3 newPos = currentPos + m_RandomDirection * m_ConfuseSpeed * dt;
            Target.transform.position = newPos;
        }
        
        // 随机攻击（这里可以添加随机攻击逻辑���
        if (Target.AttackComponent != null && Random.Range(0f, 1f) < 0.1f) // 10%概率随机攻击
        {
            // 这里可以添加随机攻击逻辑
            // Target.AttackComponent.AttackRandomTarget();
        }
    }

    protected override void OnFinish()
    {
        base.OnFinish();
        Logger.Log($"{Target.name} 混乱效果结束");
    }

    protected override void OnRemove()
    {
        base.OnRemove();
        
        // 恢复动画状���
        if (Target.Animator != null)
        {
            Target.Animator.SetBool("confused", false);
        }
        
        // 清理特效
        var effects = Target.GetComponentsInChildren<ParticleSystem>();
        foreach (var effect in effects)
        {
            if (effect.name.Contains("Confuse"))
            {
                GameObject.Destroy(effect.gameObject);
            }
        }
    }

    public override bool IsCanMerge()
    {
        return false; // 混乱效果不能叠加，只能刷新持续时���
    }
}
